package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.BookDAO;
import com.wanwanbookstore.entity.Book;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class BookListServlet extends HttpServlet {
    private BookDAO bookDAO = new BookDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // 检查是否是刷新推荐图书的请求
        String refreshRecommended = request.getParameter("refreshRecommended");
        if (refreshRecommended != null && refreshRecommended.equals("true")) {
            // 只需要重新生成推荐图书
            List<String> categories = bookDAO.getAllCategories();
            List<Book> recommendedBooks = getRecommendedBooks(bookDAO, categories);
            
            request.setAttribute("recommendedBooks", recommendedBooks);
            request.setAttribute("categories", categories);
            
            // 只转发到index.jsp，让AJAX请求获取新的推荐内容
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        
        int page = 1;
        int pageSize = 10;
        String category = request.getParameter("category");
        String keyword = request.getParameter("keyword");

        // 获取页码
        String pageStr = request.getParameter("page");
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
                if (page < 1) page = 1;
            } catch (NumberFormatException e) {
                page = 1;
            }
        }

        List<Book> books;
        int totalBooks;

        // 初始化总图书数和图书列表
        // 优先处理搜索功能
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 搜索图书
            totalBooks = bookDAO.getSearchBooksCount(keyword);
            books = bookDAO.searchBooksByTitle(keyword, page, pageSize);
            request.setAttribute("keyword", keyword);
        } 
        // 其次处理分类筛选
        else if (category != null && !category.isEmpty()) {
            totalBooks = bookDAO.getTotalBooksByCategory(category); // 先获取分类图书总数
            books = bookDAO.getBooksByCategory(category, page, pageSize);
        } 
        // 默认显示所有图书
        else {
            totalBooks = bookDAO.getTotalBooks(); // 获取所有图书总数
            books = bookDAO.getBooks(page, pageSize);
        }
        
        // 计算总页数并调整页码
        int totalPages = (int) Math.ceil((double) totalBooks / pageSize);
        // 确保总页数至少为1，避免没有数据时没有分页显示
        if (totalPages < 1) totalPages = 1;
        // 确保当前页数不超过总页数
        if (page > totalPages) page = 1;

        // 获取所有分类
        List<String> categories = bookDAO.getAllCategories();
        
        // 获取推荐图书 - 尽量包含每个种类
        List<Book> recommendedBooks = getRecommendedBooks(bookDAO, categories);

        request.setAttribute("books", books);
        request.setAttribute("recommendedBooks", recommendedBooks);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalBooks", totalBooks);
        request.setAttribute("categories", categories);
        request.setAttribute("currentCategory", category);

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
    
    /**
     * 获取推荐图书，从推荐分类中随机选择图书
     */
    private List<Book> getRecommendedBooks(BookDAO bookDAO, List<String> categories) {
        // 调用BookDAO中的方法获取推荐图书
        return bookDAO.getRecommendedBooks();
    }
}